package com.bigdatastudio.monitor.Filter;

import com.bigdatastudio.common.Enums.TableStarEnums;
import com.bigdatastudio.common.Utils.RedisUtil;
import com.bigdatastudio.common.entity.HonorWall;
import com.bigdatastudio.common.entity.Notice;
import com.bigdatastudio.notice.server.INoticeService;
import com.bigdatastudio.other.server.IHonorWallService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author xiao_jie
 * @date 2022/10/16 20:22
 * @describe   周期函数执行，每天一定时间将redis里面的数据保存到mysql
 */

@Slf4j
@Component
// order，值越小优先级就越高
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableScheduling
public class ListenHandler {


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IHonorWallService wallService;

    @Autowired
    private INoticeService noticeService;



    //  {秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}
    //  每40秒一个周期执行（设置一个时间段刷新更新到数据库）
    //  每天23点执行一次：0 0 23 * * ?   每隔5秒执行一次："*/5 * * * * ?"
    @Scheduled(cron = "0 0 23 * * ?")
    public void updateNum() {
        log.info("redis数据存入mysql周期任务开始执行...");
        TableStarEnums[] values = TableStarEnums.values();
        for (TableStarEnums item:
             values) {
            Map<Object, Object> hmget = redisUtil.hmget(item.toString());
            writeNum(hmget,item.toString());
        }
        log.info("周期任务执行完毕,redis写入数据库完毕");
    }


    private void writeNum(Map<Object, Object> map, String keyName) {
        map.forEach((k, v) -> {
            switch (keyName) {
                case "Notice":
                    Notice byId = noticeService.getById(k.toString());
                    byId.setStar((Integer) v);
                    noticeService.updateById(byId);
                    return;
                case "HonorWall":
                    HonorWall byId1 = wallService.getById(k.toString());
                    byId1.setStar((Integer) v);
                    wallService.updateById(byId1);
                    return;
                default:
                    return;
            }
        });
        log.info("{} 更新完毕", keyName);
    }

}
